﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace KC.Library.Web
{
    public class Referrers
    {
		public static bool isSearchEngineReferral(Uri Referrer, out string Engine, out string Query)
		{
			if (Referrer == null) throw new ArgumentNullException("Referrer");
			Engine = null;
			Query = null;
			// Great, Google changed their search query format again.
			if (!Referrer.AbsoluteUri.Contains("?") && Referrer.AbsoluteUri.Contains("#"))
				Referrer = new Uri(Referrer.AbsoluteUri.Replace("#", "?"));
			if (Referrer == null || string.IsNullOrEmpty(Referrer.AbsoluteUri) || !Referrer.AbsoluteUri.Contains('?') || !Referrer.AbsoluteUri.Contains('='))
				return false;

			//Format engine
			Engine = Engine = Referrer.Host.ToLower();
			if (Engine.StartsWith("www") && Engine.Substring(Engine.IndexOf("www") + 3).Contains(".")) Engine = Engine.Substring(Engine.IndexOf(".", Engine.IndexOf("www") + 3) + 1);
			if (Engine.Contains(".")) Engine = Engine.Substring(0, Engine.IndexOf("."));

			//Detect querymember, query
			System.Collections.Specialized.NameValueCollection QueryString = HttpUtility.ParseQueryString(Referrer.AbsoluteUri.Replace("?", "?randomxx-8f8d989af&"));
			foreach (string qm in new string[] { "q", "p", "query", "wd" })
				if (QueryString[qm] != null) Query = HttpUtility.UrlDecode(QueryString[qm].Trim());
			return Query != null;
		}

	}
}
